//jQuery插件，可以动态监控div的大小
(function($, h, c) {
    var a = $([]), e = $.resize = $.extend($.resize, {}), i, k = "setTimeout", j = "resize", d = j
        + "-special-event", b = "delay", f = "throttleWindow";
    e[b] = 350;
    e[f] = true;
    $.event.special[j] = {
        setup : function() {
            if (!e[f] && this[k]) {
                return false
            }
            var l = $(this);
            a = a.add(l);
            $.data(this, d, {
                w : l.width(),
                h : l.height()
            });
            if (a.length === 1) {
                g()
            }
        },
        teardown : function() {
            if (!e[f] && this[k]) {
                return false
            }
            var l = $(this);
            a = a.not(l);
            l.removeData(d);
            if (!a.length) {
                clearTimeout(i)
            }
        },
        add : function(l) {
            if (!e[f] && this[k]) {
                return false
            }
            var n;
            function m(s, o, p) {
                var q = $(this), r = $.data(this, d);
                r.w = o !== c ? o : q.width();
                r.h = p !== c ? p : q.height();
                n.apply(this, arguments)
            }
            if ($.isFunction(l)) {
                n = l;
                return m
            } else {
                n = l.handler;
                l.handler = m
            }
        }
    };
    function g() {
        i = h[k](function() {
            a.each(function() {
                var n = $(this), m = n.width(), l = n.height(), o = $
                    .data(this, d);
                if (m !== o.w || l !== o.h) {
                    n.trigger(j, [ o.w = m, o.h = l ])
                }
            });
            g()
        }, e[b])
    }
})(jQuery, this);


function loadScript(url) {
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = url;
    document.body.appendChild(script);
}

function loadStyles(url) {
    var link = document.createElement("link");
    link.type = "text/css";
    link.rel = "stylesheet";
    link.href = url;
    document.getElementsByTagName("head")[0].appendChild(link);
}

//封装post，后面使用起来更简单
function postJSON(url, data, success) {
    return jQuery.ajax({
        type: "POST",
        url: url,
        data: JSON.stringify(data),
        contentType: "application/json",
        dataType: "json",
        success: success
    });
};

function getLayerByTitle(title) {
    //先得到groupLayer，再在grouplayer里得到具体的layer,
    //第一个groupLayer是底图，第二个groupLayer是业务图层,这个函数获取的就是业务图层
    var groupLayers = map.getLayers().getArray();
    var layers = groupLayers[1].getLayers().getArray();
    for (var i = 0; i < layers.length; i++) {
        var dics = layers[i].getProperties();
        if (dics["title"] == title) {
            return layers[i];
        }
    }
    return null;
}

//"设置地图是否可见"
function setBaseLayerVisible(layerTitle) {
    var groupLayers = map.getLayers().getArray();
    var layers = groupLayers[0].getLayers().getArray();
    for (var i = 0; i < layers.length; i++) {
        var dics = layers[i].getProperties();
        if (dics["title"] == layerTitle) {
            layers[i].setVisible(true);
            return;
        }
    }
}

function getBaseLayer(title) {
    //根据配置文件中的名称获取layers,js中的底图
    var layers = BaseLayers;
    for (var i = 0; i < layers.length; i++) {
        var dics = layers[i].getProperties();
        if (dics["title"] == title) {
            return layers[i];
        }
    }
    return null;
}


function zeroPad(num, len, radix) {
    var str = num.toString(radix || 10);
    while (str.length < len) {
        str = "0" + str;
    }
    return str;
}

/*设置地图显示位置，以及显示级别*/
function setCenterZoom(x, y, zoom) {
    map.getView().setCenter([x, y]);
    map.getView().setZoom(zoom);
}

function ZoomToPositon(x, y, zoom) {
	map.getView().setCenter(ol.proj.transform([x, y], 'EPSG:4326', 'EPSG:3857'));
	map.getView().setZoom(zoom);
}

//下面两个全局变量用来保存注册的事件,函数会根据这两个变量来决定响应哪些图层的哪些事件.具体用法见文档
//格式{layerTitle:'热点',callbackFunction:func,style:stylefunc}
_mapHoverEvents=[];
//格式{layerTitle:'热点',callbackFunction:func}
_mapClickEvents=[];

function clickSearchLayers(layer) {
    var dics = layer.getProperties();
    var hasLayer=false;
    for(var i=0;i<_mapClickEvents.length;i++){
        if(_mapClickEvents[i].layerTitle==dics["title"]){
            hasLayer=true;
            break;
        }
    }
    return hasLayer
}

function hoverSearchLayers(layer) {
    var dics = layer.getProperties();
    var hasLayer=false;
    for(var i=0;i<_mapHoverEvents.length;i++){
        if(_mapHoverEvents[i].layerTitle==dics["title"]){
            hasLayer=true;
            break;
        }
    }
    return hasLayer
}


//选中feature的时候修改feature的符号,未来会取消
var changeStyle = function(feature,resolution){
//判断类型，面和点的style不同
     var selectedLayer = selectClickInteraction.getLayer(feature);
     return selectedLayer.getStyle();

};


var changeHoverStyle = function(feature,resolution){
    //判断类型，面和点的style不同
     var selectedLayer = selectHoverInteraction.getLayer(feature);
       var geomType=feature.getGeometry().getType();
       for(var i=0;i<_mapHoverEvents.length;i++){
             if (selectedLayer === getLayerByTitle(_mapHoverEvents[i].layerTitle)) {
                    if(_mapHoverEvents[i].style==undefined || _mapHoverEvents[i].style==null){
                         if(geomType=='Point'){
                             var pStyleOld= selectedLayer.getStyleFunction()(feature,resolution);
                             if(pStyleOld==undefined || pStyleOld==null){
                                 return null;
                             }
                            var pointStyle= pStyleOld.clone();

                             pointStyle.getImage().setScale(1.5);

                            /* pointStyle.setImage(new ol.style.Circle({
                                    radius:8,
                                    stroke: new ol.style.Stroke({
                                        color:'rgba(0,243,255,1)'
                                    }),
                                    fill: new ol.style.Fill({
                                        color: 'rgba(0,243,255,1)'
                                    })
                                })
                            );*/

                            return pointStyle;
                         }else if(geomType=='MultiPolygon' ||geomType=='Polygon' ){
                            /* var pStyleOld= selectedLayer.getStyleFunction()(feature,resolution);
                             if(pStyleOld==undefined || pStyleOld==null){
                                 return null;
                             }
                             var pStyle=pStyleOld.clone();
                             pStyle.setStroke(new ol.style.Stroke({
                                color: 'rgba(255,0,0,1)',
                                width: 1
                              }));
                             pStyle.setFill(new ol.style.Fill({
                                color: 'rgba(0,255,255,0.7)'
                              }));*/


                             var pStyleOld= selectedLayer.getStyleFunction()(feature,resolution);
                             if(pStyleOld==undefined || pStyleOld==null){
                                 return null;
                             }
                             var pStyle=pStyleOld.clone();
                             pStyle.setStroke(new ol.style.Stroke({
                                 color: 'rgba(254,190,62,1)',
                                 width: 2
                             }));
                             pStyle.setFill(new ol.style.Fill({
                                 color: 'rgba(152,077,255,1)'
                             }));

                             return pStyle;
                         }else if(geomType=='MultiLineString' ||geomType=='LineString' ){
                               return new ol.style.Style({
                                  stroke: new ol.style.Stroke({
                                    color: 'rgba(0,255,255,0.7)',
                                    width: 3
                                  })
                                });
                         }
                    }else{
                        if(_mapHoverEvents[i].style=='old'){
                            return selectedLayer.getStyleFunction()(feature,resolution);
                        }else{
                            return _mapHoverEvents[i].style(feature,resolution);
                        }
                    }
                    break;
             }
        }
};


function MapClickEvent(e){
    PopUp_big.hide();
    var arr=e.target;//获取事件对象，即产生这个事件的元素-->ol.interaction.Select
    var collection = arr.getFeatures();//获取这个事件绑定的features-->返回值是一个ol.Collection对象
    var features = collection.getArray();//获取这个集合的第一个元素-->真正的feature
    var dic_values = null;
    //如果有选中的要素就响应事件
    if(features.length>0){
        var feature = features[0];
        if(feature.getGeometry().getType()=='Point')
        {
            if (feature.get('features') != null && feature.get('features').length > 1) {
                //如果大于1个就是聚合图层，不弹框
                selectClickInteraction.getFeatures().clear();
                //地图level+1
                map.getView().setZoom(map.getView().getZoom()+1);
                return;
            }
        }
        //根据事件列表来决定响应哪些图层的事件
        var selectedLayer = selectClickInteraction.getLayer(feature);
        dic_values = feature.getProperties();
        selectClickInteraction.getFeatures().clear();
        for(var i=0;i<_mapClickEvents.length;i++){
             if (selectedLayer === getLayerByTitle(_mapClickEvents[i].layerTitle)) {
                    //点线面弹出的位置不同
                    var point=null;
                    if(feature.getGeometry().getType()=='Point')
                    {
                        point=feature.getGeometry().getCoordinates();
                        //如果是聚合图层中的单个点，要获取具体的属性值
                        if (feature.get('features') != null && feature.get('features').length ==1) {
                            dic_values = feature.get('features')[0].getProperties();
                        }
                    }
                    else if(feature.getGeometry().getType()=='MultiLineString'||feature.getGeometry().getType()=='LineString')
                    {
                        point=ol.extent.getCenter(feature.getGeometry().getExtent());
                    }
                    else if(feature.getGeometry().getType()=='MultiPolygon'||feature.getGeometry().getType()=='Polygon')
                    {
                        if(feature.getGeometry().getType()=='MultiPolygon'){
                             var polygons = feature.getGeometry().getPolygons();
                             var centerpoint=polygons[0].getInteriorPoint();
                             point=centerpoint.getCoordinates();
                        }else{
                             var centerpoint=feature.getGeometry().getInteriorPoint();
                             point=centerpoint.getCoordinates();
                        }
                    }
                    if(_mapClickEvents[i].callbackFunction!=undefined){
                       _mapClickEvents[i].callbackFunction(dic_values,point);
                       return;
                    }
                    break;
             }
        }
     }
}

function MapHoverEvent(e){
    var arr=e.target;//获取事件对象，即产生这个事件的元素-->ol.interaction.Select
    var collection = arr.getFeatures();//获取这个事件绑定的features-->返回值是一个ol.Collection对象
    var features = collection.getArray();//获取这个集合的第一个元素-->真正的feature
    var dic_values = null;
    //如果有选中的要素就响应事件
    PopUp_ToolTip.hide();
    PopUp_ToolTip2.hide();
    if(features.length>0){
        var feature = features[0];
        if(feature.getGeometry().getType()=='Point')
        {
            if (feature.get('features') != null && feature.get('features').length > 1) {
                //如果大于1个就是聚合图层，不弹框
                map.getTargetElement().style.cursor = 'pointer';
                return;
            }
        }
        map.getTargetElement().style.cursor = 'pointer';
        //根据事件列表来决定响应哪些图层的事件
        var selectedLayer = selectHoverInteraction.getLayer(feature);
        dic_values = feature.getProperties();
        for(var i=0;i<_mapHoverEvents.length;i++){
             if (selectedLayer === getLayerByTitle(_mapHoverEvents[i].layerTitle)) {
                    //点线面弹出的位置不同
                    var point=null;
                    if(feature.getGeometry().getType()=='Point')
                    {
                        point=feature.getGeometry().getCoordinates();
                        //如果是聚合图层中的单个点，要获取具体的属性值
                        if (feature.get('features') != null && feature.get('features').length ==1) {
                            dic_values = feature.get('features')[0].getProperties();
                        }
                    }
                    else if(feature.getGeometry().getType()=='MultiLineString'||feature.getGeometry().getType()=='LineString')
                    {
                        point=ol.extent.getCenter(feature.getGeometry().getExtent());
                    }
                    else if(feature.getGeometry().getType()=='MultiPolygon'||feature.getGeometry().getType()=='Polygon')
                    {
                        if(feature.getGeometry().getType()=='MultiPolygon'){
                             var polygons = feature.getGeometry().getPolygons();
                             var centerpoint=polygons[0].getInteriorPoint();
                             point=centerpoint.getCoordinates();
                        }else{
                             var centerpoint=feature.getGeometry().getInteriorPoint();
                             point=centerpoint.getCoordinates();
                        }
                    }
                    if(_mapHoverEvents[i].callbackFunction!=undefined){
                        _mapHoverEvents[i].callbackFunction(dic_values,point);
                        return;
                    }

                    break;
             }
        }
     }else{
         //当hover没有选中要素的时候鼠标就恢复默认状态
         map.getTargetElement().style.cursor = '';
        for(var i=0;i<_mapHoverEvents.length;i++){
            if(_mapHoverEvents[i].callbackFunctionOut!=undefined){
                _mapHoverEvents[i].callbackFunctionOut();
            }
        }
     }
}

function addMapClickEvent(evt){
     _mapClickEvents.push(evt);
     selectClickInteraction.un("select",MapClickEvent);
     map.removeInteraction(selectClickInteraction);
     selectClickInteraction.on("select",MapClickEvent);
     map.addInteraction(selectClickInteraction);
}

function addMapHoverEvent(evt){
    _mapHoverEvents.push(evt);
     selectHoverInteraction.un("select",MapHoverEvent);
     map.removeInteraction(selectHoverInteraction);
     selectHoverInteraction.on("select",MapHoverEvent);
     map.addInteraction(selectHoverInteraction);
}

function removeMapClickEvent(layerTitle){
     for (var i=_mapClickEvents.length-1;i>=0;i--){
        if(_mapClickEvents[i].layerTitle==layerTitle){
             _mapClickEvents.splice(i,1);
             selectClickInteraction.un("select",MapClickEvent);
             map.removeInteraction(selectClickInteraction);
             selectClickInteraction.on("select",MapClickEvent);
             map.addInteraction(selectClickInteraction);
             return;
        }
    }
}

function removeMapHoverEvent(layerTitle){
    for (var i=_mapHoverEvents.length-1;i>=0;i--){
        if(_mapHoverEvents[i].layerTitle==layerTitle){
             _mapHoverEvents.splice(i,1);
             selectHoverInteraction.un("select",MapHoverEvent);
             map.removeInteraction(selectHoverInteraction);
             selectHoverInteraction.on("select",MapHoverEvent);
             map.addInteraction(selectHoverInteraction);
             return;
        }
    }
}

/*加载配置文件*/
var appconfig;
$.ajaxSettings.async = false;
$.getJSON(getJSPathbyName("gis.js") + "config.json", function (data) {
    appconfig = data;
    var apptitle = $("#apptitle");
    //apptitle[0].innerText = appconfig.title;//系统名称
    document.title = appconfig.title;//系统名称
    //设置中心,从配置文件中读取初始化位置，级别
    var initX = appconfig.map.mapOptions.extent.x;
    var initY = appconfig.map.mapOptions.extent.y;
    var initLevel = appconfig.map.mapOptions.extent.level;
    var coor = ol.proj.transform([initX, initY], 'EPSG:4326', 'EPSG:3857');
    globalView = new ol.View({
        center: coor,
        zoom: initLevel,
        minZoom: 8,
        maxZoom: 18,
        extent:[13101473.05776755,3984185.368606994,13428623.538828103,4219917.163838478]
    });

    //鹰眼控件初始化
    var overviewMapControl = new ol.control.OverviewMap({
        // see in overviewmap-custom.html to see the custom CSS used
        className: 'ol-overviewmap ol-custom-overviewmap',
        layers: [
            WYLLayer,
            TDTImgLayer,
            TDTVecLayer
        ],
        collapseLabel: '\u00BB',
        label: '\u00AB',
        collapsed: true
    });

    map = new ol.Map({
        target: 'map',
        loadTilesWhileAnimating: true,
        loadTilesWhileInteracting: true,
        layers: [
            new ol.layer.Group({
                'title': '底图',
                layers: [
                    //ColorLayer
                ]
            }),
            YWLayer = new ol.layer.Group({
                title: '图层',
                layers: []
            }),
        ],
        controls: ol.control.defaults({attribution: false}).extend([
            /*overviewMapControl,
            new ol.control.Rotate(),
            new ol.control.ZoomSlider(),

            new ol.control.ZoomToExtent({
                extent: [13161240.046070673,4047522.602736721,13454758.234685749,4173949.4475204023],
                label: 'E', tipLabel: '缩放至全图范围'
            }),
            //new ol.control.LayerSwitcher(),

            new ol.control.MapSwitch(),
            new ol.control.MousePosition({
                coordinateFormat: ol.coordinate.createStringXY(8),
                projection: 'EPSG:4326',
                className: 'custom-mouse-position',
                target: document.getElementById('mouse-position')
            }),
            new ol.control.ScaleLine({
                units: "metric",//设置比例尺单位，有degrees、imperial、us、nautical或metric
                target: document.getElementById('scale-line')//显示比例尺的目标容器
            }),*/
        ]),
        view: globalView
    });


    //控制地图div变动随动
    $("#" + mapContainer).resize(function(){
        //地图的大小也要跟div一样，否则会出现鼠标和地图上的点坐标不一致，最直观的bug就是空间点选查询不准
        map.setSize([$("#" + mapContainer).width(),$("#" + mapContainer).height()]);
    });
    map.setSize([$("#" + mapContainer).width(),$("#" + mapContainer).height()]);
    //大弹框
    PopUp_big = new ol.Overlay.Popup (
        {
            popupClass: "black", //"tooltips", "warning" "black" "default", "tips", "shadow",
            closeBox: false,
            onshow: function(){ },
            onclose: function(){ },
            positioning: 'auto',
            autoPan: true,
            autoPanAnimation: { duration: 250 }
        });
    map.addOverlay(PopUp_big);
    //提示框
    PopUp_ToolTip = new ol.Overlay.Popup(
        {
            popupClass: "tips", //"tooltips", "warning" "black" "default", "tips", "shadow",
            closeBox: false,
            positioning: 'bottom-left',
            autoPan: false,
            autoPanAnimation: { duration: 250 }
        });
    map.addOverlay(PopUp_ToolTip);

    PopUp_ToolTip2 = new ol.Overlay.Popup(
                  {
                      popupClass: "default", //"tooltips", "warning" "black" "default", "tips", "shadow",
                      closeBox: false,
                      positioning: 'bottom-left',
                      autoPan: false,
                      autoPanAnimation: { duration: 250 }
                  });
    map.addOverlay(PopUp_ToolTip2);

    //设置地图点击交互
    selectClickInteraction = new ol.interaction.Select({
            condition: ol.events.condition.click,
            style:changeStyle,
            layers: clickSearchLayers
            });
    selectHoverInteraction = new ol.interaction.Select({
            condition: ol.events.condition.pointerMove,
            style:changeHoverStyle,
            layers: hoverSearchLayers
    });
})
